﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MuXue.Zyiz.Template.Common.Redis
{
    public class RedisConn
    {
        public static ConnectionMultiplexer RedisConnBySentinel(IConfigurationSection _config)
        {
            RedisCloudConfiguration RedisCloud = JsonConvert.DeserializeObject<RedisCloudConfiguration>(HttpHelper.HttpPost(_config["RedisSentinelsUrl"], "", "application/x-www-form-urlencoded"));
            ConfigurationOptions sentinelConfig = new ConfigurationOptions();
            string[] sentinelArr = RedisCloud.sentinels.Split(' ');
            foreach (string sentinel in sentinelArr)
            {
                sentinelConfig.EndPoints.Add(sentinel);
            }
            //这行在sentinel模式必须加上
            sentinelConfig.TieBreaker = "";
            // Need Version 3.0 for the INFO command?
            sentinelConfig.CommandMap = CommandMap.Sentinel;
            sentinelConfig.AllowAdmin = true;
            sentinelConfig.SyncTimeout = 15000;
            sentinelConfig.KeepAlive = 180;
            sentinelConfig.ConnectRetry = 3;
            ConnectionMultiplexer sentinelConnection = ConnectionMultiplexer.Connect(sentinelConfig);
            var sentinelEndpoint = sentinelConnection.GetEndPoints().Select
            (endpoint =>
            {
                var server = sentinelConnection.GetServer(endpoint);
                if (server.IsConnected)
                {
                    return server;
                }
                return null;
            }).FirstOrDefault();

            var redisEndpoint = sentinelEndpoint.SentinelGetMasterAddressByName(RedisCloud.masterName);
            ConfigurationOptions redisConfig = new ConfigurationOptions();
            redisConfig.EndPoints.Add(redisEndpoint);
            redisConfig.AbortOnConnectFail = false;
            redisConfig.KeepAlive = 180;
            redisConfig.SyncTimeout = 15000;
            redisConfig.ConnectRetry = 3;
            return ConnectionMultiplexer.Connect(redisConfig);
        }
    }
    public class RedisCloudConfiguration
    {
        public string sentinels { get; set; }
        public string message { get; set; }
        public int status { get; set; }
        public string masterName { get; set; }
        public int appId { get; set; }
    }
}
